package com.xatz.scanner

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.xatz.scanner.bean.DataTable
import com.xatz.scanner.bean.TotalDatasBean
import com.xatz.scanner.databinding.FragmentTotalPageBinding
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
import java.io.StringReader

/**
 * author: tdq
 * date: 2021/7/20
 * description: 汇总
 */
class TotalPageFragment : Fragment() {
    private lateinit var mBinding: FragmentTotalPageBinding

    private val mService by lazy {
        ScannerRetrofitClient().getService(
            ScannerService::class.java,
            ScannerService.baseUrl
        )
    }

    private var mDatas: MutableList<TotalDatasBean> = mutableListOf()

    private var mLists: MutableList<TotalDatasBean> = mutableListOf()

    private var totalDatasBean: TotalDatasBean? = null

    private var name = ""

    private lateinit var mAdapter: MyAdapter

    private var map: HashMap<String, TotalDatasBean> = hashMapOf()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentTotalPageBinding.inflate(inflater, container, false)
        mAdapter = MyAdapter(mLists)
        mBinding.rvDetails.adapter = mAdapter
        return mBinding.root
    }

    fun onScannerResult(data: DataTable?) {
        data?.run {
            requireActivity().runOnUiThread {
                mBinding.tvOrder.text = C_DELIVERY
                mBinding.tvCarNum.text = C_PLATE_NUMBER
                getOutDatas(C_DELIVERY)
            }
        }
    }

    fun onScannerResult(soCode: String) {
        getOutDatas(soCode)
    }

    fun clearData() {
        mBinding.tvOrder.text = ""
        mBinding.tvCarNum.text = ""
        mDatas.clear()
        mLists.clear()
        map.clear()
        mAdapter.notifyDataSetChanged()
    }

    private fun getOutDatas(code: String) {
        mService.getOutDatas(code).enqueue(object : Callback<String> {
            @SuppressLint("SetTextI18n")
            override fun onResponse(call: Call<String>, response: Response<String>) {
                if (response.isSuccessful) {
                    response.body()?.let { tabStr ->
                        mLists.clear()
                        map.clear()
                        parseXMLWithPull(tabStr)
                        mDatas.forEach {
                            name = if (it.guige.contains("Φ")) {
                                it.c_str_grd + it.guige
                            } else {
                                it.c_str_grd + "Φ" + it.guige
                            }

                            if (map.containsKey(name)) {
                                val totalDatasBean = map[name]
                                totalDatasBean?.wgt = (totalDatasBean?.wgt?.toDouble()?.plus(it.wgt.toDouble())).toString()
                                totalDatasBean?.count = totalDatasBean?.count?.plus(1)!!
                            } else {
                                map[name] = TotalDatasBean(it.c_str_grd, it.guige, it.wgt, 1)
                            }
                        }
                        mDatas.clear()
                        mLists.addAll(map.values)
                        mAdapter.notifyDataSetChanged()
                    }
                }
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
            }

        })
    }

    private fun parseXMLWithPull(xmlData: String) {
        mDatas.clear()
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullParser = factory.newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))
            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when (eventType) {
                    XmlPullParser.START_DOCUMENT -> {
                    }
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "Table" -> {
                                totalDatasBean = TotalDatasBean("", "", "", 0)
                            }
                            "C_STR_GRD" -> totalDatasBean?.c_str_grd = xmlPullParser.nextText()
                            "GUIGE" -> totalDatasBean?.guige = xmlPullParser.nextText()
                            "N_WGT" -> totalDatasBean?.wgt = xmlPullParser.nextText()
                        }
                    }
                    XmlPullParser.END_TAG -> {
                        if ("Table" == xmlPullParser.name) {
                            totalDatasBean?.let { mDatas.add(it) }
                            totalDatasBean = null
                        }
                    }
                }
                eventType = xmlPullParser.next()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    class MyAdapter(private val valueList: MutableList<TotalDatasBean>) :
        RecyclerView.Adapter<MyViewHolder>() {

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): MyViewHolder {
            return MyViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_details, parent, false)
            )
        }

        override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
            try {
                holder.tvNum?.text = valueList[position].c_str_grd
                holder.tvType?.text = valueList[position].count.toString()
                holder.tvWeight?.text = valueList[position].wgt
                holder.tvGuiGe?.text = valueList[position].guige
                holder.tvGuiGe?.visibility = View.VISIBLE
            } catch (e: Exception) {
                Timber.e(e)
            }
        }

        override fun getItemCount(): Int {
            return valueList.size
        }
    }

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tvNum: TextView? = null
        var tvType: TextView? = null
        var tvWeight: TextView? = null
        var tvGuiGe: TextView? = null

        init {
            tvNum = itemView.findViewById(R.id.tvNum)
            tvType = itemView.findViewById(R.id.tvType)
            tvGuiGe = itemView.findViewById(R.id.tvGuiGe)
            tvWeight = itemView.findViewById(R.id.tvWeight)
        }
    }
}